{ Google Code Jam 2011. Qualification Round.
  Problemset: http://code.google.com/codejam/contest/dashboard?c=975485#
  Problem B
  Verdict: Correct/Correct
}
type
    let='A'..'Z';

var
   i,j,n,t,cr,k,m,ls:longint;
   s,rs:string;
   ch,cha,chb,chc:char;
   inv:array[let,let] of char;
   cnt:array[let] of longint;
   opp:array[let,0..110] of char;
   f:array[let] of boolean;
   g:boolean;
begin
reset(input,'input.txt');
rewrite(output,'output.txt');
read(t);
for i:=1 to t do begin
    fillchar(inv,sizeof(inv),'.');
    fillchar(cnt,sizeof(cnt),0);
    fillchar(opp,sizeof(opp),'.');
    fillchar(f,sizeof(f),false);
    read(n);
    for j:=1 to n do begin
        read(ch,cha,chb,chc);
        inv[cha][chb]:=chc;
        inv[chb][cha]:=chc;
    end;
    read(n);
    for j:=1 to n do begin
        read(ch,cha,chb);
        inc(cnt[cha]);
        inc(cnt[chb]);
        opp[cha][cnt[cha]]:=chb;
        opp[chb][cnt[chb]]:=cha;
    end;
    read(n);
    s:='';
    cr:=0;
    read(ch);
    for j:=1 to n do begin
        read(ch);
        if cr>0 then begin
           if inv[ch][s[cr]]<>'.' then begin
              if pos(s[cr],s)=cr then f[s[cr]]:=false;
              s[cr]:=inv[ch][s[cr]];
              f[s[cr]]:=true;
           end else begin
               g:=true;
               for k:=1 to cnt[ch] do begin
                   if f[opp[ch][k]] then begin
                      ls:=length(s);
                      for m:=1 to ls do f[s[m]]:=false;
                      s:='';
                      cr:=0;
                      g:=false;
                      break;
                   end;
               end;
               if g then begin
                  f[ch]:=true;
                  inc(cr);
                  s:=s+ch;
               end;
           end;
        end else begin
            inc(cr);
            s:=S+ch;
            f[ch]:=true;
        end;
    end;
    rs:='[';
    ls:=length(s)-1;
    for j:=1 to ls do rs:=rs+s[j]+', ';
    inc(ls);
    if ls>0 then rs:=rs+s[ls];
    rs:=rs+']';
    writeln('Case #',i,': ',rs);
    readln;
end;
end.                                    